package com.jeecms.wicool.action.activies;

import static com.jeecms.common.page.SimplePage.cpn;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.JOptionPane;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import com.jeecms.cms.entity.main.CmsUser;
import com.jeecms.cms.manager.main.CmsLogMng;
import com.jeecms.cms.web.CmsUtils;
import com.jeecms.cms.web.WebErrors;
import com.jeecms.common.page.Pagination;
import com.jeecms.common.web.CookieUtils;
import com.jeecms.wicool.entity.activities.Activities;
import com.jeecms.wicool.entity.activities.ActivitiesApply;
import com.jeecms.wicool.entity.activities.ActivitiesApplyToExcel;
import com.jeecms.wicool.entity.cms.CmsInfo;
import com.jeecms.wicool.entity.cms.CmsVote;
import com.jeecms.wicool.entity.shops.ShopInfo;
import com.jeecms.wicool.manager.activities.ActivitiesApplyMng;
import com.jeecms.wicool.manager.activities.ActivitiesMng;
import com.jeecms.wicool.manager.cms.CmsInfoMng;
import com.jeecms.wicool.manager.shops.WiShopInfoMng;
import com.jeecms.wicool.util.ExportExcel;
import com.jeecms.wicool.util.Student;
import com.mchange.v2.log.LogUtils;

/**
 * 组织活动
 * @author hujie
 *
 */
@Controller
public class ActivitiesAct {
	private static final Logger log = LoggerFactory.getLogger(ActivitiesAct.class);
	
	@Autowired
	private ActivitiesMng manager;
	@Autowired
	private CmsLogMng cmsLogMng;
	@Autowired
	private ActivitiesApplyMng applyMng;
	@Autowired
	private CmsInfoMng cmsInfoMng;
	@Autowired
	private WiShopInfoMng shopMng;
	
	@RequestMapping("/activities/v_list.do") 
	public String list(String title,Date publishDate,Integer pageNo,HttpServletRequest request, ModelMap model) {
		
		Pagination pagination = manager.getPage(title,publishDate,cpn(pageNo),
				CookieUtils.getPageSize(request));
		model.addAttribute("pagination", pagination);
		model.addAttribute("title", title);
		model.addAttribute("publishDate", publishDate);
		return "activities/list_activities";
	}
	
	@RequestMapping("/activities/v_edit.do")
	public String edit(Integer id,String title,Date publishDate, HttpServletRequest request, ModelMap model) {
		WebErrors errors = WebErrors.create(request);
		Activities activities = manager.findById(id);
		if (errors.ifNotExist(activities, Activities.class, id)) {
			return errors.showErrorPage(model);
		}
		DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		model.addAttribute("activities", activities);
		model.addAttribute("publishTime",format.format(activities.getPublishTime()).toString());
		model.addAttribute("endTime", format.format(activities.getEndTime()).toString());
		model.addAttribute("q_publishTime", format.format(activities.getPublishTime()));
		model.addAttribute("q_title", title);
		List<ShopInfo> listShop= shopMng.getAll(CmsUtils.getUser(request));
		model.addAttribute("listShop", listShop);
		return "activities/edit_activities";
	}
	@RequestMapping("/activities/v_view.do")
	public String view(Integer id, HttpServletRequest request, ModelMap model) {
		WebErrors errors = WebErrors.create(request);
		Activities activities = manager.findById(id);
		if (errors.ifNotExist(activities, Activities.class, id)) {
			return errors.showErrorPage(model);
		}
		DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		model.addAttribute("activities", activities);
		model.addAttribute("publishTime",format.format(activities.getPublishTime()).toString());
		model.addAttribute("endTime", format.format(activities.getEndTime()).toString());
		List<ShopInfo> listShop= shopMng.getAll(CmsUtils.getUser(request));
		model.addAttribute("listShop", listShop);
		return "activities/view_activities";
	}
	@RequestMapping("/activities/o_save.do")
	public String save(Activities bean,Integer shopId,HttpServletRequest request, ModelMap model) {
		bean.setStatus("0");
		bean.setUpdateTime(new Date());
		CmsUser user = CmsUtils.getUser(request);
		bean.setPublisher(user.getUsername());
		bean.setPublisherId(user.getId().toString());
		bean.setShop(shopMng.findById(shopId));
		log.info("save Activities id={}", bean.getSid());
		manager.save(bean);
		return "redirect:v_list.do";
	}
	@RequestMapping("/activities/o_update.do")
	public String update(Activities bean,Integer shopId,String q_title,Date q_publishDate,Integer pageNo,HttpServletRequest request,ModelMap model) {
		bean.setUpdateTime(new Date());
		bean.setShop(shopMng.findById(shopId));
		manager.update(bean);
		return list(q_title, q_publishDate, pageNo, request, model);
	}
	
	@RequestMapping("/activities/v_add.do")
	public String add(ModelMap model,HttpServletRequest request) {
		model.addAttribute("publisherName", CmsUtils.getUser(request).getUsername());
		Date nowTime = new Date();
		DateFormat simpleFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		model.addAttribute("publishTime", simpleFormat.format(nowTime));
		List<ShopInfo> listShop= shopMng.getAll(CmsUtils.getUser(request));
		model.addAttribute("listShop", listShop);
		return "activities/add_activities";
	}
	

	@RequestMapping("/activities/o_delete.do")
	public String delete(Integer[] ids, String title,Date publishDate,Integer pageNo, HttpServletRequest request,
			ModelMap model) {
		WebErrors errors = validateDelete(ids, request);
		if (errors.hasErrors()) {
			return errors.showErrorPage(model);
		}
		ArrayList<Activities> activities= manager.deleteByIds(ids);
		return list(title,publishDate,pageNo, request, model);
	}
	
	@RequestMapping("/activities/V_publish.do")
	public String pulishView(Integer id,String title,Date publishDate,Integer pageNo,HttpServletRequest request,ModelMap model) {
		Activities entity = manager.findById(id);
		WebErrors errors = WebErrors.create(request);
		if (errors.ifNotExist(entity, Activities.class, id)) {
			return errors.showErrorPage(model);
		}
		entity.setPublishTime(new Date());
		entity.setUpdateTime(new Date());
		entity.setStatus("1");
		manager.update(entity);
		//把 投票页面链接同步到cms_vote表中
				//TODO
				CmsInfo ci=new CmsInfo();
				ci.setTitle(entity.getTitle());
				ci.setCmsPath(request.getScheme()+"://"+ request.getServerName()+":"+request.getServerPort()+request.getContextPath()+"/activities.jspx?activitiesId="+entity.getSid());
				ci.setOrderNum(entity.getSid());
				ci.setPublisher(CmsUtils.getUser(request));
				ci.setTitleImage(entity.getTitlePicURL());
				ci.setContentId(entity.getSid());
				ci.setIsIndex(Short.valueOf("1"));
				ci.setStatus(Short.parseShort("-1"));
				ci.setIndexType(1);
				cmsInfoMng.save(ci, entity.getShop().getId());
		
		return list(null, null, pageNo, request, model);
	}
	@RequestMapping("/activities/V_qxpublish.do")
	public String qxpulishView(Integer id,String title,Date publishDate,Integer pageNo,HttpServletRequest request,ModelMap model) {
		Activities entity = manager.findById(id);
		WebErrors errors = WebErrors.create(request);
		if (errors.ifNotExist(entity, Activities.class, id)) {
			return errors.showErrorPage(model);
		}
		entity.setStatus("0");
		manager.update(entity);
		
		//把 投票页面链接从cms_vote表中删除
				//TODO
		     CmsInfo ci=cmsInfoMng.findByContentId(entity.getSid());
				if(ci!=null){
					cmsInfoMng.deleteById(ci.getId());
				}
		return list(null, null, pageNo, request, model);
	}
	/**
	 * 发布活动方法 ---------作废
	 * @param id
	 * @param title
	 * @param publishDate
	 * @param logoUrl
	 * @param pageNo
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("/activities/o_updateStatus.do")
	public String updateStatus(Integer id,String title,Date publishDate,String logoUrl,Integer pageNo,HttpServletRequest request,ModelMap model) {
		Activities entity = manager.findById(id);
		WebErrors errors = WebErrors.create(request);
		if (errors.ifNotExist(entity, Activities.class, id)) {
			return errors.showErrorPage(model);
		}
		entity.setStatus("1");
		entity.setPublishTime(new Date());
		entity.setUpdateTime(new Date());
		entity.setTitlePicURL(logoUrl);
		manager.update(entity);
		
		CmsInfo cmsInfo = new CmsInfo();
		cmsInfo.setTitle(entity.getTitle());
		cmsInfo.setPublisher(CmsUtils.getUser(request));
		cmsInfo.setTitleImage(logoUrl);
		cmsInfo.setContentId(entity.getSid());
		return list(title, publishDate, pageNo, request, model);
	}
	
	@RequestMapping("/activities/v_applyList.do")
	public String applyList(Integer id,String name,String phoneNumber,Integer pageNo,HttpServletRequest request,ModelMap model) {
		Pagination pagination = applyMng.getPage(id,name,phoneNumber,cpn(pageNo),
				CookieUtils.getPageSize(request));
		model.addAttribute("pagination", pagination);
		model.addAttribute("name", name);
		model.addAttribute("id", id);
		model.addAttribute("phoneNumber", phoneNumber);
		return "activities/list_activitiesapply";
	}
	@RequestMapping("/activities/v_exportExcel.do")
	public String exportExcel(Integer id,Integer pageNo,HttpServletRequest request,HttpServletResponse response,ModelMap model) {
		
		List<ActivitiesApply> aaList = applyMng.findByPsid(id);
		if(aaList!=null&&aaList.size()>0){
			ExportExcel<ActivitiesApplyToExcel> ex = new ExportExcel<ActivitiesApplyToExcel>();
			String[] headers =
				{ "活动标题", "姓名", "手机号码", "留言", "提交时间" };
			List<ActivitiesApplyToExcel> dataset = new ArrayList<ActivitiesApplyToExcel>();
			for(ActivitiesApply aa:aaList){
				dataset.add(new ActivitiesApplyToExcel(aa.getActivities().getTitle(),aa.getName(),aa.getPhoneNumber()
						,aa.getMessage(),aa.getSubmitTime()));
			}
			 OutputStream out ;

			try {
				SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
				String fileName="activities_"+df.format(new Date())+".xls";
				response.setContentType("octets/stream");
		        response.addHeader("Content-Disposition",
		                "attachment;filename="+fileName);
				out = response.getOutputStream();
				ex.exportExcel(headers, dataset, out,"yyyy-MM-dd HH:mm:ss");
				out.close();
				System.out.println("excel导出成功！");
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			
		}else{
			model.addAttribute("message", "exportExcel.failed.not.have.apply");
		}
		return list(null, null, pageNo, request, model);
	}
	private WebErrors validateDelete(Integer[] ids, HttpServletRequest request) {
		WebErrors errors = WebErrors.create(request);
		errors.ifEmpty(ids, "ids");
		for (Integer id : ids) {
			vldExist(id, errors);
		}
		return errors;
	}

	private boolean vldExist(Integer id, WebErrors errors) {
		if (errors.ifNull(id, "id")) {
			return true;
		}
		Activities entity = manager.findById(id);
		if (errors.ifNotExist(entity, Activities.class, id)) {
			return true;
		}
		return false;
	}
	
}
